import random
import re
from collections import OrderedDict

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from . import constants
from users.models import User
from django.http import JsonResponse
from django.http import Http404

# Create your views here.
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView, CreateAPIView, ListAPIView, RetrieveAPIView, UpdateAPIView

from .serializers import CreateRoleSerializer, ForgetAdminPasswordSerializer, \
    DeleteAdminSerializer, ChangeAdminStatusSerializer, UserMobileSendSMSCodeSerializer, AdminChangeMobileSerializer, \
    ChangeAdminPasswordSerializer, DisplayAllAdminSerializer, SuperUserChangeAdminSerializer


class AdminPagination(PageNumberPagination):
    """
    商品列表自定义分页
    """
    # 默认每页显示的个数
    page_size = 12
    # 可以动态改变 每页显示的个数
    page_size_query_param = 'page_size'
    # 页码参数
    page_query_param = 'page'
    # 最多能显示多少页
    max_page_size = 100

    # 自定义返回参数
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            # ('next', self.get_next_link()),
            # ('previous', self.get_previous_link()),
            ('results', data),
            ('current_page', self.page.number),
            ('ResultCode', 1),
        ]))


# 获取用户名数量
class UsernameCountView(APIView):
    """
    用户名数量
    """

    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username, is_deleted=False).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# 获取手机号数量
class MobileCountView(APIView):
    """
    手机号数量
    """

    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


class AdminLoginView(APIView):
    """
    用户登陆
    resultcode:
        1 : 登录成功
        2 : 用户不存在
        3 : 密码错误
        4 : 用户已失效
    """

    def post(self, request):
        userName = request.data.get('userName')
        passWord = request.data.get('passWord')
        try:
            user = User.objects.get(username=userName)
        except Exception as e:
            return JsonResponse({'ResultCode': 2, 'message': '用户不存在'})

        # 判断用户是否是合法用户(启用或者未启用,删除或者未删除)
        # active_status = (
        #     (0, '未启用'),
        #     (1, '已启用'),
        # )
        if user.active_status == 1 and user.is_deleted is False:
            if user.check_password(raw_password=passWord):
                # 手动生成JWT
                # 手动生成token验证
                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)

                ret = {}

                # 手机号码返回时需要加密
                mobile = re.sub(r'(\d{3})(\d{4})(\d{4})', r'\1****\2', user.mobile)
                ret['ResultCode'] = 1
                ret['message'] = '登陆成功'
                ret['data'] = {
                    'token': token,
                    'user_id': user.id,
                    'realname': user.realname,
                    'role': user.role,
                    'mobile': mobile,
                    'gender': user.gender,
                    'username': user.username,
                }
                return JsonResponse(ret)
            else:
                return JsonResponse({'ResultCode': 3, 'message': '密码错误'})
        else:
            return JsonResponse({"ResultCode": 4, 'message': '用户已失效'})


class CreateRoleView(CreateAPIView):
    """
    添加管理员
    ResultCode:
        0:只有超管才能创建
        1:创建成功
    """
    serializer_class = CreateRoleSerializer

    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        user = self.request.user
        if user.is_superuser is True:
            super().create(request, *args, **kwargs)
            return Response({'message': '创建成功', 'ResultCode': 1}, status=status.HTTP_201_CREATED)
        else:
            return Response({'message': "只有超级管理员才能创建", 'ResultCode': 0}, status=status.HTTP_403_FORBIDDEN)


class AdminChangeMobileView(UpdateAPIView):
    """
    管理员添加手机号码
    resultcode:
        0:修改失败
        1:修改成功
    """
    serializer_class = AdminChangeMobileSerializer
    queryset = User.objects.all()
    permission_classes = [IsAuthenticated]

    lookup_field = 'username'

    def post(self, request, username):
        user_name = self.request.user.username
        if str(user_name) == str(username):
            # 执行父类的update方法
            self.update(request, username)
            return Response({'message': "修改成功", 'ResultCode': 1}, status=status.HTTP_201_CREATED)
        else:
            return Response({'message': "用户不一致", 'ResultCode': 0}, status=status.HTTP_403_FORBIDDEN)


# class AdminDetailView(RetrieveAPIView):
#     """
#     展示管理员相关信息
#     """
#     serializer_class = AdminDetailSerializer
#     permission_classes = [IsAuthenticated]
#
#     def get_object(self):
#         return self.request.user


class ForgetAdminPasswordView(UpdateAPIView):
    """
    忘记密码
    """
    serializer_class = ForgetAdminPasswordSerializer
    queryset = User.objects.all()

    lookup_field = 'username'

    def post(self, request, username):
        self.update(request, username)
        return Response({'ResultCode': 1, 'message': '密码重置成功'})


class ChangeAdminPasswordView(UpdateAPIView):
    """
    重置密码
    """
    serializer_class = ChangeAdminPasswordSerializer
    queryset = User.objects.all()
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        user_id = self.request.user.id
        if int(user_id) == int(pk):
            self.update(request, pk)
            return Response({'ResultCode': 1, 'message': '密码重置成功'})
        else:
            return Response({'message': "用户id不一致", 'ResultCode': 0})


class DeleteAdminView(UpdateAPIView):
    """
    删除管理员
    ResultCode:
        0:失败，超级管理员不能删除自己
        1:成功
        2:失败，只有超级管理员才能删除
    """
    serializer_class = DeleteAdminSerializer
    permission_classes = [IsAuthenticated]
    lookup_field = 'username'

    def get_queryset(self):
        username = self.kwargs['username']
        return User.objects.filter(username=username, is_deleted=False)

    def post(self, request, username):
        user = self.request.user
        if user.is_superuser is True:
            if str(user) == str(username):
                return Response({'message': '超级管理员不能删除自己', 'ResultCode': 0}, status=status.HTTP_403_FORBIDDEN)
            else:
                self.update(request, username)
                return Response({'message': '删除成功', 'ResultCode': 1})
        else:
            return Response({'message': "只有超级管理员才能删除", 'ResultCode': 2}, status=status.HTTP_403_FORBIDDEN)


class ChangeAdminStatusView(UpdateAPIView):
    """
    启用/禁用管理员
    """
    serializer_class = ChangeAdminStatusSerializer
    permission_classes = [IsAuthenticated]
    queryset = User.objects.filter(is_deleted=False)

    lookup_field = 'username'

    def post(self, request, username):
        user = self.request.user
        if user.is_superuser is True:
            if str(user) == str(username):
                return Response({'message': '超级管理员不能禁用自己', 'Resultcode': 0}, status=status.HTTP_400_BAD_REQUEST)
            else:
                self.update(request, username)
                return Response({'message': '修改成功', 'Resultcode': 1})
        else:
            return Response({'message': "只有超级管理员才有此权限", 'ResultCode': 0}, status=status.HTTP_403_FORBIDDEN)


# 发送短信验证码
class SMSCodeView(GenericAPIView):
    """
    手机号码发送短信验证码
    ResultCode:
        0:失败
        1:成功
    """
    serializer_class = UserMobileSendSMSCodeSerializer

    def get(self, request, mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存验证码以及发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_REDIS_EXPIRES, 1)
        # 让管道执行命令
        pl.execute()

        # 发送短信验证码
        # cloopen(mobile,sms_code)

        return Response({'message': '发送成功', 'ResultCode': 1})


class UserMobileRelatedView(APIView):
    def get(self):
        """
        获取指定手机号数量
        """
        params = self.request.data
        user = params.get('username')
        mobile = params.get('mobile')
        count = User.objects.filter(username=user, mobile=mobile, is_deleted=False).count()

        data = {
            'count': count
        }

        return Response(data)


# 运营人员管理
class DisplayAllAdminView(ListAPIView):
    serializer_class = DisplayAllAdminSerializer
    pagination_class = AdminPagination

    # queryset = User.objects.filter(role__in=(2, 3), is_deleted=False)
    # lookup_field = 'role'
    def get_queryset(self):
        """返回视图使用的查询集"""
        role = self.kwargs['role']
        if int(role) not in (0, 1, 2):
            raise Http404()
        if int(role) == int(0):
            return User.objects.filter(role__in=(1, 2), is_deleted=False).order_by('id')
        else:
            return User.objects.filter(role=int(role), is_deleted=False).order_by('id')

    # 针对进行了分页的情况
    def list(self, request, *args, **kwargs):
        # 继承list方法
        # print('current_page:',current_page)
        temp = super().list(request, *args, **kwargs)
        data = temp.data.get('results')
        for i in range(len(data)):
            data[i]['date_joined'] = data[i]['date_joined'][0:10]
        return temp

    def get(self, request, *args, **kwargs):
        try:
            return self.list(request, *args, **kwargs)
        except:
            return Response({'ResultCode': 0, 'message': "请求失败"}, status=status.HTTP_400_BAD_REQUEST)

    # 针对未进行分页的情况
    # def list(self, request,*args, **kwargs):
    #     # 继承list方法
    #     temp = super().list(request, *args, **kwargs)
    #     # 修改加入时间，只取年月日
    #     data = temp.data
    #     for i in range(len(data)):
    #         data[i]['date_joined'] = data[i]['date_joined'][0:10]
    #     return temp


# 超级管理员 修改普通运营或者客服的手密码
class SuperUserChangeAdminView(UpdateAPIView):
    serializer_class = SuperUserChangeAdminSerializer
    permission_classes = [IsAuthenticated]
    queryset = User.objects.filter(is_deleted=False)
    lookup_field = 'username'

    def post(self, request, username):
        user = self.request.user
        if user.is_superuser is True:
            self.update(request, username)
            return Response({'message': '密码重置成功', 'Resultcode': 1})
        else:
            return Response({'message': "只有超级管理员才有此权限", 'ResultCode': 0}, status=status.HTTP_403_FORBIDDEN)
